package com.huiquan.management.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.huiquan.analysis.domain.User;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.management.service.CompanyService;

@Controller
public class CompanyController {

	@Autowired
	private CompanyService companyService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/management/company_list.htm")
	public ModelAndView list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String tabid = req.getParameter("tabid");
		// 维护页面参数到session
		Map<String, Object> pageParam;
		if (tabid != null && !tabid.isEmpty()) {
			pageParam = new HashMap<>();
			pageParam.put("tabid", tabid);

			req.getSession().setAttribute("pageParam", pageParam);
		} else {
			pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
		}

		return companyService.list();
	}

	@ResponseBody
	@RequestMapping(value = "/management/update_company.do")
	public ReturnData updateCompany(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String id = req.getParameter("id");
		String type = req.getParameter("type");
		String value = req.getParameter("value");
		User user = (User) req.getSession().getAttribute("user");

		return companyService.updateCompany(Long.parseLong(id), user, type, value);
	}

	@ResponseBody
	@RequestMapping(value = "/management/delete_company.do")
	public ReturnData delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String id = req.getParameter("id");

		return companyService.delete(Long.parseLong(id));
	}

	@ResponseBody
	@RequestMapping(value = "/management/add_company.do")
	public ReturnData add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		String id = req.getParameter("id");
		String name = req.getParameter("name");
		String type = req.getParameter("type");
		String contractFlag = req.getParameter("contractFlag");

		return companyService.add(StringUtils.isBlank(id) ? 0 : Long.parseLong(id), name, type, contractFlag);
	}

}
